//
//  ResetPwd_Vm.swift
//  MikerShop
//
//  Created by eme on 2016/12/6.
//  Copyright © 2016年 eme. All rights reserved.
//

import RxSwift
import Result
import SwiftyJSON
import NetWorkCore
import ModelProtocol

/*
 owner:cy
 update:2016年12月06日10:44:12
 info: 重置密码viewmodel
 */
class ResetPwd_Vm {
    
    let validatedPassword: Observable<ValidationResult>
    let validatedRepeatPassword: Observable<ValidationResult>
    // 表示btn 是否可以点击状态
    let signupEnabled: Observable<Bool>
    /// 表示正在加载中..
    let signingIn: Observable<Bool>
    private let disposeBag = DisposeBag()
    
    let nextSuccess = PublishSubject<JSON>()
    let error = PublishSubject<MikerError>()
    private var isValidated:(isOk:Bool ,error:String) = (true,"")
    
    init(input: (
        password: Observable<String>,
        repeatPassword: Observable<(password:String,repeatPassword:String)>,
        nextTaps: Observable<String>
        ),
         validationService: RegisterValidationProtocol
        ) {
        let signingIn = ActivityIndicator()
        self.signingIn = signingIn.asObservable()
        validatedPassword = input.password.map{ username in
            return validationService.validatePassword(username)
            }.shareReplay(1)
        
        validatedRepeatPassword = input.repeatPassword.map{ item in
            return validationService.validateRepeatPassword(item.password, repeatPassword: item.repeatPassword)
            }.shareReplay(1)
        
        self.signupEnabled = Observable.combineLatest(
            validatedPassword,
            validatedRepeatPassword
        ){ password, repeatPassword in
            password.notEmpty && repeatPassword.notEmpty
            }
            .distinctUntilChanged()
            .shareReplay(1)
        
        input.nextTaps
            .filter{ _ in
                return !self.isValidated.isOk
            }
            .subscribe(onNext: {[unowned self] (_) in
                self.error.onNext(MikerError("文本录入错误", code: 601, message: self.isValidated.error))
            })
            .addDisposableTo(disposeBag)
        let inputObservables = Observable.combineLatest(input.password, input.nextTaps) { ($0, $1) }
        
        input.nextTaps
            .filter{ _ in
                return self.isValidated.isOk
            }.withLatestFrom(inputObservables)
            .map{password, phone in
                UserApi.resetpwd(phone: phone, password: password)
            }.emeRequestApiForJson(signingIn)
            .subscribe(onNext: { [unowned self] (result) in
                switch result {
                case .success(let data):
                    self.nextSuccess.onNext(data)
                case .failure(let error):
                    self.error.onNext(error)
                }
            })
            .addDisposableTo(disposeBag)
        Observable.combineLatest(
            validatedPassword,
            validatedRepeatPassword
        ) { (item1, item2) -> (isOk:Bool ,error:String) in
            
            if !item1.isValid{
                return (false,item1.message)
            }
            if !item2.isValid{
                return (false,item2.message)
            }
            return (true,"")
            }
            .subscribe(onNext: {[unowned self] (item) in
                self.isValidated = item
            })
            .addDisposableTo(disposeBag)
    }
    
}

